<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="日期" prop="energyTime">
        <el-date-picker
          v-model="queryParams.energyTime"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择日期"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="车间" prop="workshopId">
        <el-select
          v-model="queryParams.workshopId"
          placeholder="请选择车间"
          clearable
          class="!w-240px"
          @change="handleWorkshopChange"
        >
          <el-option
            v-for="item in workshopOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="能耗表" prop="energyId">
        <el-select
          v-model="queryParams.energyId"
          placeholder="请选择能耗表"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in energyOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:energy-report:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:energy-report:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column
        label="日期"
        align="center"
        prop="energyTime"
        width="180px"
        :formatter="dateFormatter3"
      />
      <el-table-column label="能耗表" align="center" prop="energyName" />
      <el-table-column label="所属车间" align="center" prop="workshopName" />
      <el-table-column label="能耗值" align="center" prop="energyValue" />
      <el-table-column label="能耗单位" align="center" prop="unitName" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:energy-report:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:energy-report:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EnergyReportForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { EnergyReportApi, EnergyReportVO } from '@/api/erp/energy/energyreport'
import { EnergyApi } from '@/api/erp/energy/energy'
import { EnergyWorkshopApi } from '@/api/erp/energy/energyworkshop'
import EnergyReportForm from './EnergyReportForm.vue'
import { dateFormatter3 } from '@/utils/formatTime'

/** ERP 能耗报表 列表 */
defineOptions({ name: 'EnergyReport' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EnergyReportVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const workshopOptions = ref<{ id: number; name: string }[]>([]) // 车间选项
const energyOptions = ref<{ id: number; name: string }[]>([]) // 能耗表选项
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  energyId: undefined,
  workshopId: undefined,
  energyTime: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EnergyReportApi.getEnergyReportPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EnergyReportApi.deleteEnergyReport(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EnergyReportApi.exportEnergyReport(queryParams)
    download.excel(data, 'ERP 能耗报表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取车间列表 */
const getWorkshopList = async () => {
  try {
    const { list } = await EnergyWorkshopApi.getEnergyWorkshopPage({ pageSize: 100 })
    workshopOptions.value = list.map((item) => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('获取车间列表失败', error)
  }
}

/** 获取能耗表列表 */
const getEnergyList = async (workshopId?: number) => {
  try {
    const params = workshopId ? { workshopId, pageSize: 100 } : { pageSize: 100 }
    const { list } = await EnergyApi.getEnergyPage(params)
    energyOptions.value = list.map((item) => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('获取能耗表列表失败', error)
  }
}

/** 处理车间选择变化 */
const handleWorkshopChange = (value: number) => {
  queryParams.energyId = undefined
  if (value) {
    getEnergyList(value)
  } else {
    getEnergyList()
  }
}

/** 初始化 **/
onMounted(() => {
  getWorkshopList()
  getEnergyList()
  getList()
})
</script>
